﻿using Authentication.Configuration;
using Common.Contract;
using Common.Service;
using Common.Util;
using System.Collections.Generic;
using System.Web.Mvc;
using Common.Service.DataTables;
using Common.Contract.Paging;
using System.Linq;
using Authentication.Model.ViewModel.Customer;
using Common.Contract.Customer.Record;
using Common.Contract.Customer.Request;
using Common.Contract.Customer;
using Common.Type;
using System;
using Common.Cache;
using Common.Contract.Warranty;
using Common.Contract.Warranty.Record;
using Common.Contract.Warranty.Request;

namespace Authentication.Web.Controller
{
    public class CustomerController : ControllerBase
    {
        #region Shop Infomation
        [HttpGet]
        [Authorize]
        public ActionResult ShopInfo()
        {
            var header = new RequestHeaderRecord
            {
                ApplicationKey = SystemConfiguration.ApplicationKey,
                CallerName = "Authentication.Web.Controller.CustomerController.ShopInfo"
            };
            ShopInfoViewModel vm = new ShopInfoViewModel { RoleIdentifiers = this.CurrentObjectRoles.Select(x => x.RoleIdentifier).ToList(), IsSupperAdmin = (string.Compare(this.CurrentUser, SystemConfiguration.SUPPER_ADMIN, true) == 0) };
            return View(vm);
        }


        [HttpPost]
        [Authorize]
        public ActionResult ShopInfo(ShopInfoViewModel vm, string btnClick)
        {
            var header = new RequestHeaderRecord
            {
                ApplicationKey = SystemConfiguration.ApplicationKey,
                UserRequest = this.CurrentUser,
                CallerName = "Authentication.Web.Controller.CustomerController.ShopInfo"
            };
            vm.RoleIdentifiers = this.CurrentObjectRoles.Select(x => x.RoleIdentifier).ToList();
            vm.IsSupperAdmin = (string.Compare(this.CurrentUser, SystemConfiguration.SUPPER_ADMIN, true) == 0);
            using (ServiceClient<ICustomer> serviceClient = new ServiceClient<ICustomer>())
            {
                ShopInfoRecord shopInf = new ShopInfoRecord
                {
                    ShopCode = vm.ShopCode,
                    ShopName = vm.ShopName,
                    ShopType = vm.ShopType,
                    Region = new RegionRecord { RegionIdentifier = vm.RegionIdentifier },
                    Province = new ProvinceRecord { Identifier = vm.ProvinceIdentifier },
                    District = new DistrictRecord { DistrictIdentifier = vm.DistrictIdentifier },
                    OwnerName = vm.OwnerName,
                    OwnerEmail = vm.OwnerEmail,
                    Address = vm.Address,
                    ISDNNo = vm.IsdnNo,
                    CellNo1 = vm.CellNo1,
                    CellNo2 = vm.CellNo2,
                    Channel = vm.Channel,
                    //BillToName = vm.BillTo,
                    BillToCode = vm.BillTo,
                    Active = vm.Active
                };

                if (btnClick.IsNullOrWhiteSpace())
                {
                    UpdateShopInfoRequest requestUpdate = new UpdateShopInfoRequest { Header = header, Record = shopInf };
                    var responseUpdate = serviceClient.Proxy.UpdateShopInfo(requestUpdate);
                    if (responseUpdate.IsSuccess)
                    {
                        return RedirectToAction("shopinfo");
                    }
                }
                else if (btnClick == "btnNewShop")
                {
                    AddShopInfoRequest requestCreate = new AddShopInfoRequest { Header = header, Record = shopInf };
                    var responseCreate = serviceClient.Proxy.AddShopInfo(requestCreate);
                    if (responseCreate.IsSuccess)
                    {
                        return RedirectToAction("shopinfo");
                    }
                }
            }

            return View(vm);
        }

        [HttpPost]
        [Authorize]
        public ActionResult ShopInfoData(DataTablesPageRequest pageRequest)
        {
            DataTableResponse pageResponse = null;
            using (ServiceClient<ICustomer> serviceClient = new ServiceClient<ICustomer>())
            {
                SearchShopInfosRequest request = new SearchShopInfosRequest
                {
                    Header = new RequestHeaderRecord
                    {
                        ApplicationKey = SystemConfiguration.ApplicationKey,
                        CallerName = "Authentication.Web.Controller.SystemController.ShopInfoData"
                    },
                    Page = new PageRecord
                    {
                        PageSize = pageRequest.DisplayLength,
                        PageIndex = pageRequest.DisplayLength > 0 ? pageRequest.DisplayStart / pageRequest.DisplayLength : 0
                    },
                    TextSearch = pageRequest.Search.Trim()
                };
                var shopInfoRecords = serviceClient.Proxy.SearchShopInfo(request);
                var resultShopInfo = (shopInfoRecords == null || shopInfoRecords.Records == null) ? new List<ShopInfoRecord>() : shopInfoRecords.Records;
                pageResponse = new DataTableResponse
                {
                    sEcho = pageRequest.Echo,
                    iTotalRecords = shopInfoRecords.Page.TotalRecords,
                    sColumns = pageRequest.ColumnNames,
                    aaData = resultShopInfo.Select(x => new object[]{
                                                             x.ShopCode,
                                                             x.ShopName,
                                                             (x.Region==null || x.Region.RegionIdentifier.IsNullOrWhiteSpace()) ?string.Empty:x.Region.RegionIdentifier,
                                                             x.Channel??string.Empty,
                                                             x.ShopType??string.Empty,
                                                             x.BillToCode??string.Empty,
                                                             x.BillToName??string.Empty,
                                                             x.OwnerName??string.Empty,
                                                             x.OwnerEmail??string.Empty,
                                                             (x.Province==null || x.Province.Identifier.IsNullOrWhiteSpace()) ?string.Empty:x.Province.Identifier,
                                                             (x.Province==null || x.Province.ProvinceName.IsNullOrWhiteSpace()) ?string.Empty:x.Province.ProvinceName,
                                                             (x.District==null || x.District.DistrictIdentifier.IsNullOrWhiteSpace()) ?string.Empty:x.District.DistrictIdentifier,
                                                             (x.District==null || x.District.DistrictName.IsNullOrWhiteSpace()) ?string.Empty:x.District.DistrictName,
                                                             x.Address??string.Empty,
                                                             x.CellNo1??string.Empty,
                                                             x.CellNo2??string.Empty,
                                                             x.Active,
                                                             x.ISDNNo??string.Empty
                    }).ToList()
                };
            }
            return Json(pageResponse);
        }

        [Authorize]
        [HttpPost]
        public ActionResult Active_Shop(string code, bool active)
        {
            var header = new RequestHeaderRecord
            {
                ApplicationKey = SystemConfiguration.ApplicationKey,
                CallerName = "Authentication.Web.Controller.AccountController.Active_Shop"
            };

            using (ServiceClient<ICustomer> serviceClient = new ServiceClient<ICustomer>())
            {
                RetrieveShopInfoRequest requestRetrieve = new RetrieveShopInfoRequest
                {
                    Header = header,
                    ShopCode = code,
                };
                var responseRetrieve = serviceClient.Proxy.RetrieveShopInfo(requestRetrieve);
                if (responseRetrieve.IsSuccess)
                {
                    responseRetrieve.Record.Active = !active;
                    UpdateShopInfoRequest request = new UpdateShopInfoRequest
                    {
                        Header = header,
                        Record = responseRetrieve.Record
                    };
                    var response = serviceClient.Proxy.UpdateShopInfo(request);
                    return Json((ResponseRecord)response);
                }
                return Json((ResponseRecord)responseRetrieve);
            }
        }
        #endregion

        #region region
        [Authorize]
        public ActionResult Regions()
        {
            RegionsViewModel vm = new RegionsViewModel { IsSupperAdmin = CurrentUser.Equals(SystemConfiguration.SUPPER_ADMIN, StringComparison.OrdinalIgnoreCase) };
            return View(vm);
        }


        [HttpPost]
        [Authorize]
        public ActionResult Regions(RegionsViewModel vm, string btnClick)
        {
            var header = new RequestHeaderRecord
            {
                ApplicationKey = SystemConfiguration.ApplicationKey,
                CallerName = "Authentication.Web.Controller.Customer.Region"
            };

            var record = new RegionRecord
            {
                RegionIdentifier = vm.RegionIdentifier,
                RegionName = vm.Name
            };

            using (ServiceClient<ICustomer> serviceClient = new ServiceClient<ICustomer>())
            {
                ResponseRecord response = null;
                if (btnClick == "btnNewRegion")
                {
                    AddRegionRequest request = new AddRegionRequest
                    {
                        Header = header,
                        Record = record
                    };
                    response = serviceClient.Proxy.AddRegion(request);
                }
                else
                {
                    UpdateRegionRequest request = new UpdateRegionRequest
                    {
                        Header = header,
                        Record = record
                    };
                    response = serviceClient.Proxy.UpdateRegion(request);
                }

                if (response.IsSuccess)
                {
                    CacheFactory.MemCache.RemoveFromCache(CACHING_NAME.LIST_ALL_REGIONS);
                    return RedirectToAction("regions", "customer");
                }
                else
                {
                    vm.Message = response.ErrorMessage;
                    vm.MessageType = MessageType.Error;
                    vm.IsSupperAdmin = CurrentUser.Equals(SystemConfiguration.SUPPER_ADMIN, StringComparison.OrdinalIgnoreCase);
                }
            }
            return View(vm);
        }

        [HttpPost]
        [Authorize]
        public ActionResult RegionData(DataTablesPageRequest pageRequest)
        {
            DataTableResponse pageResponse = null;
            using (ServiceClient<ICustomer> serviceClient = new ServiceClient<ICustomer>())
            {
                SearchRegionsRequest request = new SearchRegionsRequest
                {
                    Header = new RequestHeaderRecord
                    {
                        ApplicationKey = SystemConfiguration.ApplicationKey,
                        CallerName = "Authentication.Web.Controller.CustommerController.RegionData"
                    },
                    Page = new PageRecord
                    {
                        PageSize = pageRequest.DisplayLength,
                        PageIndex = pageRequest.DisplayLength > 0 ? pageRequest.DisplayStart / pageRequest.DisplayLength : 0
                    },
                    TextSearch = pageRequest.Search.Trim()
                };
                var regionRecord = serviceClient.Proxy.SearchRegions(request);
                var resultApplication = (regionRecord == null || regionRecord.Records == null) ? new List<RegionRecord>() : regionRecord.Records;
                pageResponse = new DataTableResponse
                {
                    sEcho = pageRequest.Echo,
                    iTotalRecords = regionRecord.Page.TotalRecords,
                    sColumns = pageRequest.ColumnNames,
                    aaData = resultApplication.Select(x => new object[]{x.RegionIdentifier,
                                                                        x.RegionName}).ToList()
                };
            }
            return Json(pageResponse);
        }

        [Authorize]
        [HttpPost]
        public ActionResult Delete_Region(string code)
        {
            using (ServiceClient<ICustomer> serviceClient = new ServiceClient<ICustomer>())
            {
                var regionRecord = new RegionRecord()
                {
                    RegionIdentifier = code,
                    RegionName = ""
                };
                DeleteRegionRequest request = new DeleteRegionRequest
                {
                    Header = new RequestHeaderRecord
                    {
                        ApplicationKey = SystemConfiguration.ApplicationKey,
                        CallerName = "Authentication.Web.Controller.CustomerController.Delete_Region"
                    },
                    Record = regionRecord
                };
                var response = serviceClient.Proxy.DeleteRegion(request);
                CacheFactory.MemCache.RemoveFromCache(CACHING_NAME.LIST_ALL_REGIONS);
                return Json(response);
            }
        }
        #endregion

        #region Province
        [Authorize]
        public ActionResult Provinces()
        {
            ModelState.Clear();
            var header = new RequestHeaderRecord
            {
                ApplicationKey = SystemConfiguration.ApplicationKey,
                CallerName = "Authentication.Web.Controller.CustomerControl.Provinces"
            };

            ProvincesViewModel vm = new ProvincesViewModel { IsSupperAdmin = CurrentUser.Equals(SystemConfiguration.SUPPER_ADMIN, StringComparison.OrdinalIgnoreCase) };

            return View(vm);
        }

        [HttpPost]
        [Authorize]
        public ActionResult Provinces(ProvincesViewModel vm)
        {
            var header = new RequestHeaderRecord
            {
                ApplicationKey = SystemConfiguration.ApplicationKey,
                CallerName = "Authentication.Web.Controller.Customer.Provinces"
            };

            var record = new ProvinceRecord
            {
                LAT = vm.Lat,
                LNG = vm.Lng,
                Identifier = vm.Identifier,
                ProvinceName = vm.ProvinceName,
                RegionIdentifier = vm.RegionIdentifier
            };

            using (ServiceClient<ICustomer> serviceClient = new ServiceClient<ICustomer>())
            {
                ResponseRecord response = null;
                if (string.IsNullOrWhiteSpace(vm.Identifier))
                {
                    AddProvinceRequest request = new AddProvinceRequest
                    {
                        Header = header,
                        Record = record
                    };
                    response = serviceClient.Proxy.AddProvince(request);
                }
                else
                {
                    UpdateProvinceRequest request = new UpdateProvinceRequest
                    {
                        Header = header,
                        Record = record
                    };
                    response = serviceClient.Proxy.UpdateProvince(request);
                }

                if (response.IsSuccess)
                {
                    CacheFactory.MemCache.RemoveFromCache(CACHING_NAME.LIST_ALL_PROVINCES);
                    return RedirectToAction("provinces", "customer");
                }
                else
                {
                    vm.Message = response.ErrorMessage;
                    vm.MessageType = MessageType.Error;
                    vm.IsSupperAdmin = CurrentUser.Equals(SystemConfiguration.SUPPER_ADMIN, StringComparison.OrdinalIgnoreCase);
                }
            }
            return View(vm);
        }

        [HttpPost]
        [Authorize]
        public ActionResult ProvincesData(DataTablesPageRequest pageRequest)
        {
            DataTableResponse pageResponse = null;
            using (ServiceClient<ICustomer> serviceClient = new ServiceClient<ICustomer>())
            {
                SearchProvincesRequest request = new SearchProvincesRequest
                {
                    Header = new RequestHeaderRecord
                    {
                        ApplicationKey = SystemConfiguration.ApplicationKey,
                        CallerName = "Authentication.Web.Controller.CustommerController.ProvincesData"
                    },
                    Page = new PageRecord
                    {
                        PageSize = pageRequest.DisplayLength,
                        PageIndex = pageRequest.DisplayLength > 0 ? pageRequest.DisplayStart / pageRequest.DisplayLength : 0
                    },
                    TextSearch = pageRequest.Search.Trim()
                };
                var provincesRecord = serviceClient.Proxy.SearchProvinces(request);
                var resultApplication = (provincesRecord == null || provincesRecord.Records == null) ? new List<ProvinceRecord>() : provincesRecord.Records;
                pageResponse = new DataTableResponse
                {
                    sEcho = pageRequest.Echo,
                    iTotalRecords = provincesRecord.Page.TotalRecords,
                    sColumns = pageRequest.ColumnNames,
                    aaData = resultApplication.Select(x => new object[]{x.ProvinceName, 
                                                                        x.LNG, 
                                                                        x.LAT,
                                                                        x.Region==null?string.Empty: x.Region.RegionName, 
                                                                        x.Identifier, 
                                                                        x.Region==null?string.Empty: x.Region.RegionIdentifier, 
                                                                        true
                    }).ToList()
                };
            }
            return Json(pageResponse);
        }

        [Authorize]
        [HttpPost]
        public ActionResult Delete_Province(string code)
        {
            using (ServiceClient<ICustomer> serviceClient = new ServiceClient<ICustomer>())
            {
                var provinceRecord = new ProvinceRecord()
                {
                    Identifier = code
                };
                DeleteProvinceRequest request = new DeleteProvinceRequest
                {
                    Header = new RequestHeaderRecord
                    {
                        ApplicationKey = SystemConfiguration.ApplicationKey,
                        CallerName = "Authentication.Web.Controller.CustomerController.Delete_Province"
                    },
                    Record = provinceRecord
                };
                var response = serviceClient.Proxy.DeleteProvince(request);
                CacheFactory.MemCache.RemoveFromCache(CACHING_NAME.LIST_ALL_PROVINCES);
                return Json(response);
            }
        }

        #endregion

        #region Districts
        [Authorize]
        public ActionResult Districts()
        {
            ModelState.Clear();
            var header = new RequestHeaderRecord
            {
                ApplicationKey = SystemConfiguration.ApplicationKey,
                CallerName = "Authentication.Web.Controller.CustomerControl.Districts"
            };

            DistrictsViewModel vm = new DistrictsViewModel { IsSupperAdmin = CurrentUser.Equals(SystemConfiguration.SUPPER_ADMIN, StringComparison.OrdinalIgnoreCase) };

            return View(vm);
        }

        [HttpPost]
        [Authorize]
        public ActionResult Districts(DistrictsViewModel vm)
        {
            var header = new RequestHeaderRecord
            {
                ApplicationKey = SystemConfiguration.ApplicationKey,
                CallerName = "Authentication.Web.Controller.Customer.Districts"
            };

            var record = new DistrictRecord
            {
                LAT = vm.Lat,
                LNG = vm.Lng,
                DistrictIdentifier = vm.DistrictIdentifier,
                DistrictName = vm.DistrictName,
                ProvinceIdentifier = vm.ProvinceIdentifier
            };

            using (ServiceClient<ICustomer> serviceClient = new ServiceClient<ICustomer>())
            {
                ResponseRecord response = null;
                if (string.IsNullOrWhiteSpace(vm.DistrictIdentifier))
                {
                    AddDistrictRequest request = new AddDistrictRequest
                    {
                        Header = header,
                        Record = record
                    };
                    response = serviceClient.Proxy.AddDistrict(request);
                }
                else
                {
                    UpdateDistrictRequest request = new UpdateDistrictRequest
                    {
                        Header = header,
                        Record = record
                    };
                    response = serviceClient.Proxy.UpdateDistrict(request);
                }

                if (response.IsSuccess)
                {
                    CacheFactory.MemCache.RemoveFromCache(CACHING_NAME.LIST_ALL_DISTRICTS);
                    return RedirectToAction("districts", "customer");
                }
                else
                {
                    vm.Message = response.ErrorMessage;
                    vm.MessageType = MessageType.Error;
                    vm.IsSupperAdmin = CurrentUser.Equals(SystemConfiguration.SUPPER_ADMIN, StringComparison.OrdinalIgnoreCase);
                }
            }
            return View(vm);
        }

        [HttpPost]
        [Authorize]
        public ActionResult DistrictsData(DataTablesPageRequest pageRequest)
        {
            DataTableResponse pageResponse = null;
            using (ServiceClient<ICustomer> serviceClient = new ServiceClient<ICustomer>())
            {
                SearchDistrictsRequest request = new SearchDistrictsRequest
                {
                    Header = new RequestHeaderRecord
                    {
                        ApplicationKey = SystemConfiguration.ApplicationKey,
                        CallerName = "Authentication.Web.Controller.CustommerController.DistrictsData"
                    },
                    Page = new PageRecord
                    {
                        PageSize = pageRequest.DisplayLength,
                        PageIndex = pageRequest.DisplayLength > 0 ? pageRequest.DisplayStart / pageRequest.DisplayLength : 0
                    },
                    TextSearch = pageRequest.Search.Trim()
                };
                var districtRecord = serviceClient.Proxy.SearchDistricts(request);
                var resultApplication = (districtRecord == null || districtRecord.Records == null) ? new List<DistrictRecord>() : districtRecord.Records;
                pageResponse = new DataTableResponse
                {
                    sEcho = pageRequest.Echo,
                    iTotalRecords = districtRecord.Page.TotalRecords,
                    sColumns = pageRequest.ColumnNames,
                    aaData = resultApplication.Select(x => new object[]{x.DistrictName, x.LNG, x.LAT,
                                                            x.Province==null?string.Empty: x.Province.ProvinceName, x.DistrictIdentifier, x.Province==null?string.Empty: x.Province.Identifier, true}).ToList()
                };
            }
            return Json(pageResponse);
        }

        [Authorize]
        [HttpPost]
        public ActionResult Delete_District(string code)
        {
            using (ServiceClient<ICustomer> serviceClient = new ServiceClient<ICustomer>())
            {
                var districtRecord = new DistrictRecord()
                {
                    DistrictIdentifier = code
                };
                DeleteDistrictRequest request = new DeleteDistrictRequest
                {
                    Header = new RequestHeaderRecord
                    {
                        ApplicationKey = SystemConfiguration.ApplicationKey,
                        CallerName = "Authentication.Web.Controller.CustomerController.Delete_District"
                    },
                    Record = districtRecord
                };
                var response = serviceClient.Proxy.DeleteDistrict(request);
                CacheFactory.MemCache.RemoveFromCache(CACHING_NAME.LIST_ALL_DISTRICTS);
                return Json(response);
            }
        }

        #endregion

        #region organization
        [Authorize]
        public ActionResult Organizations()
        {
            OrganizationsViewModel vm = new OrganizationsViewModel { IsSupperAdmin = CurrentUser.Equals(SystemConfiguration.SUPPER_ADMIN, StringComparison.OrdinalIgnoreCase) };
            return View(vm);
        }


        [HttpPost]
        [Authorize]
        public ActionResult Organizations(OrganizationsViewModel vm, string btnClick)
        {
            var header = new RequestHeaderRecord
            {
                ApplicationKey = SystemConfiguration.ApplicationKey,
                CallerName = "Authentication.Web.Controller.Customer.Organization"
            };

            var record = new OrganizationRecord
            {
                OrgCode = vm.OrgCode,
                OrgName = vm.OrgName,
                Description = vm.Description
            };

            using (ServiceClient<ICustomer> serviceClient = new ServiceClient<ICustomer>())
            {
                ResponseRecord response = null;
                if (btnClick == "btnNewOrganization")
                {
                    AddOrganizationRequest request = new AddOrganizationRequest
                    {
                        Header = header,
                        Record = record
                    };
                    response = serviceClient.Proxy.AddOrganization(request);
                }
                else
                {
                    UpdateOrganizationRequest request = new UpdateOrganizationRequest
                    {
                        Header = header,
                        Record = record
                    };
                    response = serviceClient.Proxy.UpdateOrganization(request);
                }

                if (response.IsSuccess)
                {
                    CacheFactory.MemCache.RemoveFromCache(CACHING_NAME.LIST_ALL_ORGANIZATION);
                    return RedirectToAction("organizations", "customer");
                }
                else
                {
                    vm.Message = response.ErrorMessage;
                    vm.MessageType = MessageType.Error;
                    vm.IsSupperAdmin = CurrentUser.Equals(SystemConfiguration.SUPPER_ADMIN, StringComparison.OrdinalIgnoreCase);
                }
            }
            return View(vm);
        }

        [HttpPost]
        [Authorize]
        public ActionResult OrganizationsData(DataTablesPageRequest pageRequest)
        {
            DataTableResponse pageResponse = null;
            using (ServiceClient<ICustomer> serviceClient = new ServiceClient<ICustomer>())
            {
                SearchOrganizationsRequest request = new SearchOrganizationsRequest
                {
                    Header = new RequestHeaderRecord
                    {
                        ApplicationKey = SystemConfiguration.ApplicationKey,
                        CallerName = "Authentication.Web.Controller.CustommerController.OrganizationsData"
                    },
                    Page = new PageRecord
                    {
                        PageSize = pageRequest.DisplayLength,
                        PageIndex = pageRequest.DisplayLength > 0 ? pageRequest.DisplayStart / pageRequest.DisplayLength : 0
                    },
                    TextSearch = pageRequest.Search.Trim()
                };
                var organizationRecord = serviceClient.Proxy.SearchOrganizations(request);
                var resultApplication = (organizationRecord == null || organizationRecord.Records == null) ? new List<OrganizationRecord>() : organizationRecord.Records;
                pageResponse = new DataTableResponse
                {
                    sEcho = pageRequest.Echo,
                    iTotalRecords = organizationRecord.Page.TotalRecords,
                    sColumns = pageRequest.ColumnNames,
                    aaData = resultApplication.Select(x => new object[]{x.OrgCode,
                                                                        x.OrgName, x.Description}).ToList()
                };
            }
            return Json(pageResponse);
        }

        [Authorize]
        [HttpPost]
        public ActionResult Delete_Organization(string code)
        {
            using (ServiceClient<ICustomer> serviceClient = new ServiceClient<ICustomer>())
            {
                var organizationRecord = new OrganizationRecord()
                {
                    OrgCode = code,
                    OrgName = ""
                };
                DeleteOrganizationRequest request = new DeleteOrganizationRequest
                {
                    Header = new RequestHeaderRecord
                    {
                        ApplicationKey = SystemConfiguration.ApplicationKey,
                        CallerName = "Authentication.Web.Controller.CustomerController.Delete_Organization"
                    },
                    Record = organizationRecord
                };
                var response = serviceClient.Proxy.DeleteOrganization(request);
                CacheFactory.MemCache.RemoveFromCache(CACHING_NAME.LIST_ALL_ORGANIZATION);
                return Json(response);
            }
        }
        #endregion

        #region response SMS
        [Authorize]
        public ActionResult Response_SMS()
        {
            ResponseSMSViewModel vm = new ResponseSMSViewModel { IsSupperAdmin = CurrentUser.Equals(SystemConfiguration.SUPPER_ADMIN, StringComparison.OrdinalIgnoreCase) };
            return View(vm);
        }


        [HttpPost]
        [Authorize]
        public ActionResult Response_SMS(ResponseSMSViewModel vm, string btnClick)
        {
            var header = new RequestHeaderRecord
            {
                ApplicationKey = SystemConfiguration.ApplicationKey,
                CallerName = "Authentication.Web.Controller.Customer.ResponseSMSs"
            };

            var record = new ResponseSMSRecord
            {
                GabitTemplate = vm.GabitTemplate,
                MsgBodyLen = vm.MsgBodyLen,
                Purpose = vm.Purpose,
                RespMsg1 = vm.RespMsg1,
                RespMsg2 = vm.RespMsg2,
                RespType = vm.RespType,
                Template = vm.Template
            };

            using (ServiceClient<IWarranty> serviceClient = new ServiceClient<IWarranty>())
            {
                ResponseRecord response = null;
                UpdateResponseSMSRequest request = new UpdateResponseSMSRequest
                {
                    Header = header,
                    Record = record
                };
                response = serviceClient.Proxy.UpdateResponseSMS(request);

                if (response.IsSuccess)
                {
                    return RedirectToAction("response-sms", "customer");
                }
                else
                {
                    vm.Message = response.ErrorMessage;
                    vm.MessageType = MessageType.Error;
                    vm.IsSupperAdmin = CurrentUser.Equals(SystemConfiguration.SUPPER_ADMIN, StringComparison.OrdinalIgnoreCase);
                }
            }
            return View(vm);
        }

        [HttpPost]
        [Authorize]
        public ActionResult ResponseSMSDate(DataTablesPageRequest pageRequest)
        {
            DataTableResponse pageResponse = null;
            using (ServiceClient<IWarranty> serviceClient = new ServiceClient<IWarranty>())
            {
                SearchResponseSMSRequest request = new SearchResponseSMSRequest
                {
                    Header = new RequestHeaderRecord
                    {
                        ApplicationKey = SystemConfiguration.ApplicationKey,
                        CallerName = "Authentication.Web.Controller.CustommerController.ResponseSMSs"
                    },
                    Page = new PageRecord
                    {
                        PageSize = pageRequest.DisplayLength,
                        PageIndex = pageRequest.DisplayLength > 0 ? pageRequest.DisplayStart / pageRequest.DisplayLength : 0
                    },
                    TextSearch = pageRequest.Search.Trim()
                };
                var responseSMSRecord = serviceClient.Proxy.SearchResponseSMS(request);
                var resultApplication = (responseSMSRecord == null || responseSMSRecord.Records == null) ? new List<ResponseSMSRecord>() : responseSMSRecord.Records;
                pageResponse = new DataTableResponse
                {
                    sEcho = pageRequest.Echo,
                    iTotalRecords = responseSMSRecord.Page.TotalRecords,
                    sColumns = pageRequest.ColumnNames,
                    aaData = resultApplication.Select(x => new object[]{x.RespType, x.MsgBodyLen, x.RespMsg1, x.RespMsg2,
                                                                        x.GabitTemplate, x.Template, x.Purpose, x.CreateDate.ToString(SystemConfiguration.DateTimeFormat)}).ToList()
                };
            }
            return Json(pageResponse);
        }
        #endregion

        #region IncentiveAdhoc
        [Authorize]
        public ActionResult Incentive_Adhoc()
        {
            IncentiveAdhocViewModel vm = new IncentiveAdhocViewModel { IsSupperAdmin = CurrentUser.Equals(SystemConfiguration.SUPPER_ADMIN, StringComparison.OrdinalIgnoreCase) };
            return View(vm);
        }

        [HttpPost]
        [Authorize]
        public ActionResult SearchIncentiveAdhoc(DataTablesPageRequest pageRequest, string btnClick, string schemename, string startdate, string enddate)
        {
            DataTableResponse pageResponse = null;
            using (ServiceClient<ICustomer> serviceClient = new ServiceClient<ICustomer>())
            {
                SearchIncentiveAdhocRequest request = new SearchIncentiveAdhocRequest()
                {
                    Header = new RequestHeaderRecord
                    {
                        ApplicationKey = SystemConfiguration.ApplicationKey,
                        CallerName = "Authentication.Web.Controller.Customer.SearchIncentiveAdhoc",
                        UserRequest = CurrentUser
                    },
                    Page = new PageRecord
                    {
                        PageSize = pageRequest.DisplayLength,
                        PageIndex = pageRequest.DisplayLength > 0 ? pageRequest.DisplayStart / pageRequest.DisplayLength : 0
                    },
                    TextSearch = pageRequest.Search,
                    SchemeName = schemename,
                    StartDate = startdate.ToDateTime(),
                    EndDate = enddate.ToDateTime()
                };

                var incentiveAdhocRecord = serviceClient.Proxy.SearchIncentiveAdhoc(request);
                var resultApplication = (incentiveAdhocRecord == null || incentiveAdhocRecord.Records == null) ? new List<IncentiveAdhocRecord>() : incentiveAdhocRecord.Records;
                pageResponse = new DataTableResponse
                {
                    sEcho = pageRequest.Echo,
                    iTotalRecords = incentiveAdhocRecord.Page.TotalRecords,
                    sColumns = pageRequest.ColumnNames,
                    aaData = resultApplication.Select(x => new object[]{
                        x.SchemeId,
                        x.SchemeName,
                        x.Purpose,
                        x.StartDate.HasValue ? x.StartDate.Value.ToString(SystemConfiguration.DateTimeFormat) : string.Empty,
                        x.EndDate.HasValue ? x.EndDate.Value.ToString(SystemConfiguration.DateTimeFormat) : string.Empty,
                        x.CloseDate.HasValue ? x.CloseDate.Value.ToString(SystemConfiguration.DateTimeFormat) : string.Empty,
                        x.Mdi,
                        x.PurposeType,
                        x.BilltoCode,
                        x.Region.RegionName}).ToList()
                };
            }
            return Json(pageResponse);
        }

        [HttpPost]
        [Authorize]
        public ActionResult Incentive_Adhoc(IncentiveAdhocViewModel vm, string btnClick)
        {
            var header = new RequestHeaderRecord
            {
                ApplicationKey = SystemConfiguration.ApplicationKey,
                CallerName = "Authentication.Web.Controller.Customer.IncentiveAdhoc",
                UserRequest = CurrentUser
            };

            var record = new IncentiveAdhocRecord
            {
                BilltoCode = vm.BilltoCode,
                CloseDate = vm.CloseDate,
                CloseUser = CurrentUser,
                EndDate = vm.EndDate,
                Mdi = vm.Mdi,
                StartDate = vm.StartDate,
                Purpose = vm.Purpose,
                PurposeType = vm.PurposeType,
                Region = new RegionRecord{
                    RegionIdentifier = vm.RegionIdentifier
                },
                SchemeId = vm.SchemeCode,
                SchemeName = vm.SchemeName
            };

            using (ServiceClient<ICustomer> serviceClient = new ServiceClient<ICustomer>())
            {
                ResponseRecord response = null;
                if (btnClick == "btnNewIncentiveAdhoc")
                {
                    AddIncentiveAdhocRequest request = new AddIncentiveAdhocRequest
                    {
                        Header = header,
                        Record = record
                    };
                    response = serviceClient.Proxy.AddIncentiveAdhocDetail(request);
                }
                else
                {
                    UpdateIncentiveAdhocRequest request = new UpdateIncentiveAdhocRequest
                    {
                        Header = header,
                        Record = record
                    };
                    response = serviceClient.Proxy.UpdateIncentiveAdhoc(request);
                }

                if (response.IsSuccess)
                {
                    return RedirectToAction("incentive-adhoc", "customer");
                }
                else
                {
                    vm.Message = response.ErrorMessage;
                    vm.MessageType = MessageType.Error;
                    vm.IsSupperAdmin = CurrentUser.Equals(SystemConfiguration.SUPPER_ADMIN, StringComparison.OrdinalIgnoreCase);
                }
            }
            return View(vm);
        }

        [Authorize]
        [HttpPost]
        public ActionResult Delete_IncentiveAdhoc(string code)
        {
            using (ServiceClient<ICustomer> serviceClient = new ServiceClient<ICustomer>())
            {
                var record = new IncentiveAdhocRecord()
                {
                   SchemeId = code
                };
                DeleteIncentiveAdhocRequest request = new DeleteIncentiveAdhocRequest
                {
                    Header = new RequestHeaderRecord
                    {
                        ApplicationKey = SystemConfiguration.ApplicationKey,
                        CallerName = "Authentication.Web.Controller.CustomerController.Delete_IncentiveAdhoc",
                        UserRequest = CurrentUser
                    },
                    Record = record
                };
                var response = serviceClient.Proxy.DeleteIncentiveAdhoc(request);
                return Json(response);
            }
        }
        #endregion
    }
}
